package com.gitee.threefish.idea.spring.toolwindow.action;


import com.gitee.threefish.idea.spring.toolwindow.navigation.SpringRequestMappingNavigationItem;
import com.gitee.threefish.idea.spring.toolwindow.tree.ApiMutableTreeNode;
import com.gitee.threefish.idea.spring.toolwindow.tree.TreeNodeObject;
import com.gitee.threefish.idea.spring.toolwindow.tree.TreeObjectTypeEnum;
import com.intellij.ui.treeStructure.SimpleTree;

import javax.swing.*;
import javax.swing.tree.TreePath;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Objects;

/**
 * @author 黄川 huchuc@vip.qq.com
 * @date: 2020/6/3
 */
public class ApiTreeMouseAdapter extends MouseAdapter implements java.awt.event.ActionListener {

    private final SimpleTree apiTree;
    private JMenuItem copyItem;
    private JMenuItem navigationItem;
    private JPopupMenu popMenu;
    private JFrame jFrame;

    public ApiTreeMouseAdapter(SimpleTree apiTree) {
        this.apiTree = apiTree;
        this.jFrame = new JFrame();
        popMenu = new JPopupMenu();
        copyItem = new JMenuItem("拷贝");
        copyItem.addActionListener(this);
        navigationItem = new JMenuItem("跳转");
        navigationItem.addActionListener(this);
        popMenu.add(copyItem);
        popMenu.add(navigationItem);
        jFrame.add(popMenu);
        jFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
    }

    /**
     * 从剪贴板中获取文本（粘贴）
     */
    public static String getClipboardString() {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 获取剪贴板中的内容
        Transferable trans = clipboard.getContents(null);
        if (trans != null) {
            // 判断剪贴板中的内容是否支持文本
            if (trans.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                try {
                    // 获取剪贴板中的文本内容
                    return trans.getTransferData(DataFlavor.stringFlavor).toString();
                } catch (Exception e) {
                }
            }
        }
        return null;
    }

    /**
     * 把文本设置到剪贴板（复制）
     */
    public static void setClipboardString(String text) {
        // 获取系统剪贴板
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        // 封装文本内容
        Transferable trans = new StringSelection(text);
        // 把文本内容设置到系统剪贴板
        clipboard.setContents(trans, null);
    }

    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
            doubleClick(e);
        } else if (e.getButton() == MouseEvent.BUTTON3 && e.getClickCount() == 1) {
            rightClick(e);
        }
    }

    /**
     * 双击
     *
     * @param e
     */
    private void doubleClick(MouseEvent e) {
        TreePath selPath = apiTree.getPathForLocation(e.getX(), e.getY());
        // 谨防空指针异常!双击空白处是会这样
        if (Objects.nonNull(selPath)) {
            // 获取这个路径上的最后一个组件,也就是双击的地方
            ApiMutableTreeNode node = (ApiMutableTreeNode) selPath.getLastPathComponent();
            if (Objects.nonNull(node)) {
                TreeNodeObject userObject = (TreeNodeObject) node.getUserObject();
                if (!(userObject.getTreeObjectType() == TreeObjectTypeEnum.MODULE || userObject.getTreeObjectType() == TreeObjectTypeEnum.ROOT)) {
                    SpringRequestMappingNavigationItem springRequestMappingNavigationItem = userObject.getUrlMappingPsiBasedElement();
                    if (springRequestMappingNavigationItem.canNavigate()) {
                        springRequestMappingNavigationItem.navigate(true);
                    }
                }
            }
        }
    }

    /**
     * 右键单击
     *
     * @param e
     */
    private void rightClick(MouseEvent e) {
        TreePath selPath = apiTree.getPathForLocation(e.getX(), e.getY());
        // 谨防空指针异常!双击空白处是会这样
        if (Objects.nonNull(selPath)) {
            popMenu.show(apiTree, e.getX(), e.getY());
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        ApiMutableTreeNode apiMutableTreeNode = (ApiMutableTreeNode) apiTree.getLastSelectedPathComponent();
        if (copyItem.equals(source)) {
            if (Objects.nonNull(apiMutableTreeNode)) {
                setClipboardString(apiMutableTreeNode.toString());
            }
        } else if (navigationItem.equals(source)) {
            if (Objects.nonNull(apiMutableTreeNode)) {
                TreeNodeObject userObject = (TreeNodeObject) apiMutableTreeNode.getUserObject();
                SpringRequestMappingNavigationItem springRequestMappingNavigationItem = userObject.getUrlMappingPsiBasedElement();
                if (springRequestMappingNavigationItem.canNavigate()) {
                    springRequestMappingNavigationItem.navigate(true);
                }
            }
        }
    }
}
